package com.example.db.utils;

import android.support.v4.util.ArrayMap;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 时间转换
 *
 * @author idong_xiaohei
 */
public class TimeUtils {

    private static Map<Object, Long> startMap = new ArrayMap<>();
    private static Map<Object, Long> endMap   = new ArrayMap<>();

    private static List<Object> timingList = new ArrayList<>();

    private static Object defaultTag = new Object();

    public static void begin() {
        begin(defaultTag);
    }

    public static void begin(Object tag) {
        startMap.put(tag, System.currentTimeMillis());

        timingList.add(tag);
    }

    public static void end() {
        end(defaultTag);
    }

    public static void end(Object tag) {
        endMap.put(tag, System.currentTimeMillis());

        timingList.remove(tag);
    }

    public static long time() {
        return time(defaultTag);
    }

    public static long time(Object tag) {
        try {
            if (isTiming(tag)) {
                end(tag);
            }

            long end = endMap.get(tag);
            long start = startMap.get(tag);

            return end - start;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 是否 正在计时
     */
    private static boolean isTiming(Object tag) {
        return timingList.contains(tag);
    }
}